package com.lyd.sweet.mybatis.config;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * mybatis扩展，获取数据源信息来区分不同数据源
 *
 * @author: 木木
 **/
@Component
public class DatabaseTypeProvider implements DatabaseIdProvider {
    private static Logger logger = LoggerFactory.getLogger(DatabaseTypeProvider.class);

    @Override
    public void setProperties(Properties p) {
    }

    @Override
    public String getDatabaseId(DataSource dataSource) throws SQLException {
        try (Connection conn = dataSource.getConnection()) {
            String dbName = conn.getMetaData().getDatabaseProductName();
            logger.info("currentDB:" + dbName);
            String dbAlias = "";
            switch (dbName) {
                case "MySQL":
                    dbAlias = "mysql";
                    break;
                //达梦
                case "DM DBMS":
                    dbAlias = "dm";
                    break;
                //人大金仓
                case "Kingbase8":
                case "KingbaseES":
                    dbAlias = "kingbase";
                    break;
                default:
                    break;
            }
            return dbAlias;
        }
    }
}
